// pages/cart/cart.js
const apiurl = require('../../config').apiurl;
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc();
Page({

  // 跳转到列表
  ShowList() {
    pulibc.navigateUrl('../list/list')
  },

  /**
   * 页面的初始数据
   */

  data: {
    invalidList: [], //失效商品
    saveHidden: true,
    cart: true,
    cartList: [],
    totalPrice: 0,
    allSelect: true,
    noSelect: false,
    delBtnWidth: 120, //删除按钮宽度单位（rpx）
  },
  // 清空失效商品
  clearInvalidGoods() {
    let list = this.data.invalidList;
    wx.showModal({
      title: '提示',
      content: '确认清空失效宝贝吗？',
      success: res => {
        if (res.confirm) {
          list.splice(0, list.length);
          this.setData({
            invalidList: list
          })
        }
      }
    })
  },
  // 单选功能
  selectTap: function(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.cartList;
    if (index !== "" && index != null) {
      //g_state为false时商品下架或库存不足
      if (list[index].g_state) {
        list[index].active = !list[index].active;
      }
      // 更新数据
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    }
    // 缓存购物车商品状态
    if (wx.getStorageSync('allSelect') || wx.getStorageSync('cartList')) {
      wx.removeStorageSync('allSelect');
      wx.removeStorageSync('noSelect');
      wx.removeStorageSync('cartList');
    }
    wx.setStorageSync('allSelect', this.data.allSelect);
    wx.setStorageSync('noSelect', this.data.noSelect);
    wx.setStorageSync('cartList', this.data.cartList);
  },
  // 全选功能
  bindAllSelect: function() {
    var currentAllSelect;
    currentAllSelect = this.data.allSelect;
    var list = this.data.cartList;
    if (currentAllSelect) {
      list.map(item => {
        item.active = false;
      })
    } else {
      list.map(item => {
        item.active = true;
      })
    }
    this.setData({
      cartList: list
    })
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), list);
    // 缓存购物车商品状态
    if (wx.getStorageSync('allSelect') || wx.getStorageSync('cartList')) {
      wx.removeStorageSync('allSelect');
      wx.removeStorageSync('noSelect');
      wx.removeStorageSync('cartList');
    }
    wx.setStorageSync('allSelect', this.data.allSelect);
    wx.setStorageSync('noSelect', this.data.noSelect);
    wx.setStorageSync('cartList', this.data.cartList);
  },
  // 控制全选按钮显示
  allSelect: function() {
    var list = this.data.cartList;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },
  // 控制全不选情况下 合计和结算显示
  noSelect: function() {
    var list = this.data.cartList;
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == list.length) {
      return true;
    } else {
      return false;
    }
  },
  // 控制合计显示
  totalPrice: function() {
    var list = this.data.cartList;
    var total = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        total += parseFloat(curItem.goods_price) * curItem.goods_num;
      }
    }
    total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
    return total;
  },
  //控制编辑状态显示
  getSaveHide: function() {
    var saveHidden = this.data.saveHidden;
    return saveHidden;
  },
  // 加
  jiaBtnTap: function(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.cartList;
    if (index !== "" && index != null) {
      // list[parseInt(index)].goods_num++;
      var tempGoodsNum = list[parseInt(index)].goods_num;
      if (!list[index].shortage) {
        tempGoodsNum++;
      }
      // 编辑购物车数量
      // 库存不足时，不再调用编辑接口
      console.log("shortage", list[index].shortage)
      if (list[index].shortage == false) {
        this.editCartData(index, list, list[parseInt(index)].cart_id, tempGoodsNum);
      }

      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

    }
  },
  // 减
  jianBtnTap: function(e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.cartList;
    if (index !== "" && index != null) {
      if (list[parseInt(index)].goods_num > 1) {
        list[parseInt(index)].goods_num--;
        // 编辑购物车数量
        list[index].shortage = false
        this.editCartData(index, list, list[parseInt(index)].cart_id, list[parseInt(index)].goods_num);
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
      }
    }
  },
  editCartData(index, list, cart_id, goods_num) {
    let that = this;
    let url = apiurl + '/membercart/cart_edit_quantity';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = cart_id;
    params.quantity = goods_num;
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success(res) {
        console.log(res)
        if (res.data.code == 200) {
          console.log(res)
          list[index].goods_num = goods_num;
          that.setData({
            cartList: list
          })
        } else {
          if (res.data.datas.error == '库存不足') {
            console.log("goods_num", goods_num)
            list[index].goods_num = goods_num - 1;
            list[index].shortage = true;
            that.setData({
              cartList: list,
            })
            console.log(list)
          }
          pulibc.showToast(res.data.datas.error, 'none');
        }
      }
    })
  },
  // 编辑
  editTap: function() {
    var list = this.data.cartList;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  saveTap: function() {
    var list = this.data.cartList;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = true;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  // 删除数据
  deleteSelected: function() {
    if (!this.data.saveHidden && this.data.noSelect) {
      pulibc.showModel('提示', '请选择删除的商品', false);
      return false;
    }
    var list = this.data.cartList;
    let ids = '';
    list = list.filter(function(item) {
      if (item.active) {
        ids += item.cart_id + ',';
      }
      return !item.active
    });
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    //调用删除接口
    ids = ids.substring(0, ids.length - 1);
    let url = apiurl + '/membercart/cart_del';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = ids;
    // params.id = this.data.cartList[0].buyer_id;
    // console.log(params)
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success(res) {
        console.log(res)

      }
    })
    console.log(list)
    // 控制所有数据删除时的显示
    if (list.length == 0) {
      this.setData({
        cart: false
      })
    }

    // console.log("cartList",this.data.cartList)
  },
  // 更新数据
  setGoodsList: function(saveHidden, total, allSelect, noSelect, list) {
    this.setData({
      saveHidden: saveHidden,
      totalPrice: total,
      allSelect: allSelect,
      noSelect: noSelect,
      cartList: list
    });
  },
  showPay() {
    if (this.data.noSelect) {
      pulibc.showModel('提示', '请先选择结算商品', false);
      return false;
    }
    let payData = [],
      ids;
    this.data.cartList.filter(item => {
      if (item.active) {
        payData.push(item.cart_id + "|" + item.goods_num)
      }
      return item.active;
    })
    ids = payData.join(',');
    console.log("ids", ids)
    pulibc.navigateUrl('../to-pay-order/to-pay-order?ids=' + ids + '&ifcart=1');
  },
  // 滑动删除
  //获取元素自适应后的实际宽度
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function(e) {
    var index = e.currentTarget.dataset.index;
    let list = e.currentTarget.dataset.list;
    let g_state = e.currentTarget.dataset.g_state;
    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      } else if (disX > 0) { //移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          left = "left:-" + delBtnWidth + "px";
        }
      }
      if (index != "" && index != null) {
        list[parseInt(index)].left = left;
        if (!g_state) {
          this.setData({
            invalidList: list
          })
        } else {
          this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
        }

      }
    }
  },

  touchE: function(e) {
    var index = e.currentTarget.dataset.index;
    let list = e.currentTarget.dataset.list;
    let g_state = e.currentTarget.dataset.g_state;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth / 2 + "px" : "margin-left:0px";
      if (index !== "" && index != null) {
        list[parseInt(index)].left = left;
        if (!g_state) {
          this.setData({
            invalidList: list
          })
        } else {
          this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

        }

      }
    }
  },
  delItem: function(e) {
    var index = e.currentTarget.dataset.index;
    let list = e.currentTarget.dataset.list;
    let g_state = e.currentTarget.dataset.g_state;
    let car_id = 0;
    list.filter((item, idx) => {
      if (idx == index) {
        car_id = item.cart_id;
      }
    })
    let url = apiurl + '/membercart/cart_del';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = car_id;
    // console.log(params)
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)
        if (res.data.code == 200) {
          // 同时删除缓存数据
          if (wx.getStorageSync('cartList')) {
            let tempList = wx.getStorageSync('cartList');
            tempList.splice(index, 1)
            if (tempList.length == 0) {
              this.setData({
                cart: false
              })
            }
            wx.setStorageSync('cartList', tempList);
          }
          list.splice(index, 1);
          if (!g_state) {
            this.setData({
              invalidList: list
            })
          } else {
            this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
            // 控制滑动删除carlist为空时 页面显示
            if (list.length == 0) {
              this.setData({
                cart: false
              })
            }
          }
        }
      }
    })
  },
  // 获取购物车列表
  getCartData() {
    var url = apiurl + '/membercart/cart_list';
    var key = wx.getStorageSync('key')
    wx.request({
      url: url,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        key
      },
      success: res => {
        if (res.data.code == 200) {
          var cartList = [];
          let totalPrice = 0;
          var allSelect = false;
          var noSelect = false;
          // 控制单选
          console.log("goods", this.data.goods)
          if (wx.getStorageSync('cartList')) {
            console.log("缓存cartList", wx.getStorageSync('cartList'))
            cartList = wx.getStorageSync('cartList');
            allSelect = wx.getStorageSync('allSelect');
            noSelect = wx.getStorageSync('noSelect');
            // console.log("allSelect",allSelect);
            if(cartList.length==0){
              wx.removeStorageSync("carList");
              this.getCartData();
            }
            // 初始化化合计数据
            cartList.map(item => {
              if (item.active) {
                totalPrice += parseFloat(item.goods_price) * item.goods_num;
              }
            })
            if (cartList.length == 1 && cartList[0].active) {
              allSelect = true;
              this.setData({
                allSelect
              })
            } else {
              this.setData({
                allSelect
              })
            }
            this.noSelect();
            this.setData({
              cartList,
              totalPrice,
              noSelect
            })
          } else {
            cartList = res.data.datas.cart_list;
            // member_gradeid 0 普通价格 1 零售价格  >1 批发价格
            let member_gradeid = res.data.datas.member_info.member_gradeid;
            cartList.map(item => {
                if (member_gradeid == 0) {
                  item.goods_price = item.goods.goods_price;
                } else if (member_gradeid == 1) {
                  item.goods_price = item.goods.retail_price;
                } else {
                  item.goods_price = item.goods.wholesale_price;
                }
            })
            console.log("不是来自于缓存", cartList)
            let validList = []; //有效商品列表
            let invalidList = []; //失效商品列表 
            cartList.map(item => {
              // 判断商品下架或不足
              if (item.g_state) {
                validList.push(item);
                item.active = true;
              } else {
                invalidList.push(item);
              }
              item.shortage = false; //用来判断库存
            })
            if (cartList.length==0) { 
              this.setData({
                cart: false
              })
            } else {
              cartList.map(item => {
                totalPrice += parseFloat(item.goods_price) * item.goods_num;
              })
              this.setData({
                cartList: validList,
                invalidList: invalidList,
                totalPrice,
                cart: true
              })

            }
          }

          console.log(this.data.cartList, "cart", this.data.cart, "invaild", this.data.invalidList)
          console.log('---------------')

        }
        else if(res.data.code == 400){
          pulibc.navigateUrl('../register/register');
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("saveHidden", this.data.saveHidden)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register"
      })
    }
    this.getCartData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})